package com.zh.sharding.sale;

import com.alibaba.fastjson.JSON;
import com.zh.mycommon.util.MyIdGenerator;
import com.zh.sharding.sale.entity.Product;
import com.zh.sharding.sale.repository.ProductDao;
import com.zh.sharding.sale.support.OperationHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author ZH
 * @date 09:13 2023/8/4
 */
@RestController
public class ProductController {
    @Autowired
    private ProductDao productDao;

    /*
    {
    "name": "小米手机",
    "store": 100,
    }
     */
    @PostMapping("/product/add")
    public Long addProduct(@RequestBody Product form) throws Exception {
        OperationHelper.log("创建新商品啦 addProduct: form = "+ JSON.toJSONString(form));

        long autoId = MyIdGenerator.autoId();
        Product product = new Product(autoId,form.getName(),form.getPrice(), form.getStore());

        productDao.insert(product);

        OperationHelper.log("新商品的ID="+autoId);
        return autoId;
    }

    @GetMapping("/product/one/{id}")
    public Product findProduct(@PathVariable Long id) throws Exception {
        OperationHelper.log("查询商品详情 findProduct: ID = "+ id);
        Product product = productDao.selectById(id);
        return product;
    }

    @GetMapping("/product/list")
    public List<Product> findProducts() {
        OperationHelper.log("查询商品列表啦 findProducts...");

        List<Product> products = productDao.selectList();
        return products;
    }
}
